/** 每页固定 10 条数据 */
const PAGE_SIZE = 10

/**
 * 滚动列表 - 下拉刷新、上拉加载更多，可复用逻辑
 */
export function createScrollListMixin(api, options = {}) {
  if (!api || typeof api !== 'function') {
    throw new Error('api must be a function')
  }

  const { pageNoField = 'pageNo', pageSizeField = 'pageSize' } = options

  return {
    data() {
      return {
        pageNo: 1,
        list: [],
        moreStatus: 'more',
        loading: false,
      }
    },
    methods: {
      async getList() {
        this.loaing = true
        try {
          if (this.pageNo > 1) {
            this.moreStatus = 'loading'
          }
          const params = {
            [pageNoField]: this.pageNo,
            [pageSizeField]: PAGE_SIZE,
          }
          const { total, records } = await api(params)
          if (this.pageNo === 1) {
            this.list = records
            this.$emit('loadend')
          } else {
            this.list = [...this.list, ...records]
          }
          this.moreStatus = this.list.length >= total ? 'noMore' : 'more'
        } finally {
          this.loading = false
        }
      },
      refresh() {
        this.pageNo = 1
        this.$emit('loadstart')
        this.getList()
      },
      update() {
        this.pageNo = 1
        this.getList()
      },
      loadMore() {
        if (['noMore', 'loading'].includes(this.moreStatus)) {
          return
        }
        this.pageNo += 1
        this.getList()
      },
    },
  }
}
